const db = require('../utils/database');
const bcrypt = require('bcrypt');

class User {
  // 根据用户名查找用户
  static findByUsername(username) {
    return new Promise((resolve, reject) => {
      db.get('SELECT * FROM users WHERE username = ?', [username], (err, row) => {
        if (err) {
          reject(err);
        } else {
          resolve(row);
        }
      });
    });
  }

  // 根据ID查找用户
  static findById(id) {
    return new Promise((resolve, reject) => {
      db.get('SELECT * FROM users WHERE id = ?', [id], (err, row) => {
        if (err) {
          reject(err);
        } else {
          resolve(row);
        }
      });
    });
  }

  // 创建新用户
  static create(username, password, role = 'user', phone = null) {
    return new Promise(async (resolve, reject) => {
      try {
        // Hash the password before storing
        const saltRounds = 10;
        const hashedPassword = await bcrypt.hash(password, saltRounds);
        
        const stmt = db.prepare('INSERT INTO users (username, password, role, phone) VALUES (?, ?, ?, ?)');
        stmt.run([username, hashedPassword, role, phone], function(err) {
          if (err) {
            reject(err);
          } else {
            resolve({ id: this.lastID, username, role, phone });
          }
        });
        stmt.finalize();
      } catch (error) {
        reject(error);
      }
    });
  }

  // 更新用户信息
  static update(id, userData) {
    return new Promise((resolve, reject) => {
      const { phone, role } = userData;
      const stmt = db.prepare('UPDATE users SET phone = ?, role = ? WHERE id = ?');
      stmt.run([phone, role, id], function(err) {
        if (err) {
          reject(err);
        } else {
          resolve({ changes: this.changes });
        }
      });
      stmt.finalize();
    });
  }

  // 删除用户
  static delete(id) {
    return new Promise((resolve, reject) => {
      const stmt = db.prepare('DELETE FROM users WHERE id = ?');
      stmt.run([id], function(err) {
        if (err) {
          reject(err);
        } else {
          resolve({ changes: this.changes });
        }
      });
      stmt.finalize();
    });
  }

  // 获取所有用户（仅限管理员）
  static findAll() {
    return new Promise((resolve, reject) => {
      db.all('SELECT id, username, role, phone, created_at FROM users', [], (err, rows) => {
        if (err) {
          reject(err);
        } else {
          resolve(rows);
        }
      });
    });
  }
}

module.exports = User;